﻿using System.IO;
using UnityEditor;
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
namespace SimpleNodeBasedEditor
{
    public class EditorDataSaveUtilities
    {
        private static EditorDataSaveUtilities m_instacne;
        public static EditorDataSaveUtilities Instance
        {
            get
            {
                if (m_instacne == null)
                {
                    m_instacne = new EditorDataSaveUtilities();
                }
                return m_instacne;
            }
        }

        #region Editor Prefers
        private string m_savePath;
        public string MainFileSavePath
        {

            get
            {
                m_savePath = EditorPrefs.GetString("SavePath", "Null");
                return m_savePath;
            }
            set
            {
                m_savePath = value;
                EditorPrefs.SetString("SavePath", m_savePath);
            }
        }
        #endregion



        public NodeWindowScriptableObject LoadPageScriptableObject(int id)
        {
            NodeWindowScriptableObject obj = AssetDatabase.LoadAssetAtPath<NodeWindowScriptableObject>(NodeWindowManager.Instance.MainData.GetPathById(id));
            return obj;
        }
        public BaseNodeWindowData ConvertToWindowData(NodeWindowScriptableObject obj)
        {
            BaseNodeWindowData windowData = new BaseNodeWindowData();
            windowData.Counter = obj.Counter;
            windowData.NodeDict = obj.ToNodeDataList();
            windowData.PageId = obj.PageId;
            windowData.WindowName = obj.WindowName;
            windowData.SaveFolder = obj.SaveFolder;
            windowData.WindowType = obj.WindowType;
            windowData.ExtensionObject = obj.ExtensionData;
            return windowData;
        }

        public void SavePage(BaseNodeWindow baseNodeWindow)
        {

            NodeWindowScriptableObject obj = ScriptableObject.CreateInstance<NodeWindowScriptableObject>();
            obj.FillData(baseNodeWindow.WindowData);

            string fullPath = Application.dataPath + "/" + obj.SaveFolder;
            string saveFolder = baseNodeWindow.WindowData.SaveFolder;
            if (string.IsNullOrEmpty(obj.SaveFolder))
            {
                EditorUtility.DisplayDialog("保存失败", "路径不能为空", "确定");
                return;
            }
            Debug.Log(fullPath);
            if (Directory.Exists(fullPath))
            {
                Directory.Delete(fullPath, true);
            }
            Directory.CreateDirectory(fullPath);
            foreach (var nodeData in obj.NodeDict)
            {
                if (nodeData!=null)
                {
                    if (nodeData.ExtensionData != null)
                    {
                        
                        AssetDatabase.CreateAsset(nodeData.ExtensionData, "Assets/" + saveFolder + "/NodeData_" + nodeData.Id + "_Extension_Obj" + ".asset");
                    }
                    AssetDatabase.CreateAsset(nodeData, "Assets/" + saveFolder + "/NodeData_" + nodeData.Id + "_" + nodeData.NodeName + ".asset");
                }
                
            }
            if (obj.ExtensionData!=null)
            {
                AssetDatabase.CreateAsset(obj.ExtensionData, "Assets/" + saveFolder + "/WindowId" + baseNodeWindow.WindowData.PageId + "_Extension_Obj" + ".asset");
            }
            AssetDatabase.CreateAsset(obj, "Assets/" + saveFolder + "/WindowId" + baseNodeWindow.WindowData.PageId + ".asset");

            if (NodeWindowManager.Instance.MainData == null)
            {
                EditorUtility.DisplayDialog("保存失败", "主数据文件损坏请重新建立！", "确定");
                return;
            }
            NodeWindowManager.Instance.MainData.AddPageData(new PageData() { pageId = baseNodeWindow.WindowData.PageId, savePath = "Assets/" + saveFolder + "/WindowId" + baseNodeWindow.WindowData.PageId + ".asset" });
            NodeWindowManager.Instance.MainData.hasLastEditorWindow = true;
            NodeWindowManager.Instance.MainData.lastEdiorPageId = baseNodeWindow.WindowData.PageId;

            //不调用不会保存 重启下就失效了
            EditorUtility.SetDirty(NodeWindowManager.Instance.MainData);
            AssetDatabase.SaveAssets();
            //更新文件后重新预加载
            NodeWindowManager.Instance.PreLoadAssets();
        }

    }



    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class OpenFileName
    {
        public int structSize = 0;
        public IntPtr dlgOwner = IntPtr.Zero;
        public IntPtr instance = IntPtr.Zero;
        public String filter = null;
        public String customFilter = null;
        public int maxCustFilter = 0;
        public int filterIndex = 0;
        public String file = null;
        public int maxFile = 0;
        public String fileTitle = null;
        public int maxFileTitle = 0;
        public String initialDir = null;
        public String title = null;
        public int flags = 0;
        public short fileOffset = 0;
        public short fileExtension = 0;
        public String defExt = null;
        public IntPtr custData = IntPtr.Zero;
        public IntPtr hook = IntPtr.Zero;
        public String templateName = null;
        public IntPtr reservedPtr = IntPtr.Zero;
        public int reservedInt = 0;
        public int flagsEx = 0;
    }

    public class WindowDll
    {
        [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
        public static bool GetOpenFileName1([In, Out] OpenFileName ofn)
        {
            return GetOpenFileName(ofn);
        }
    }
}